package com.chenwc.serialassistant;

import com.sun.jna.Platform;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.InputStream;
import java.util.Objects;

/**
 * 程序入口
 *
 * @author chenwc
 */
public class Main extends Application {

    private static final Logger logger = LoggerFactory.getLogger(Main.class);

    @Override
    public void start(Stage stage) {
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/HomePageView.fxml"));
            Parent root = fxmlLoader.load();
            Scene scene = new Scene(root);
            stage.setScene(scene);
            //设置窗口的图标
            stage.getIcons().add(new Image(Objects.requireNonNull(getClass().getResourceAsStream("/images/b2.png"))));
            stage.setTitle("串口调试助手 V1.0    作者：wxhntmy    邮箱：wxhntmy@163.com");
            stage.show();
            //窗口关闭按钮事件，防止关闭程序时没有关闭串口，当关闭窗口时结束所有进程
            stage.setOnCloseRequest((WindowEvent event) -> System.exit(0));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        loadDll();
        launch(args);
    }

    /**
     * 加载指定目录中的DLL文件
     */
    public static void loadDll() {
        String osPath = "";
        if (Platform.isWindows()) {
            if (Platform.is64Bit()) {
                osPath = "win-x64";
            } else {
                osPath = "win-x86";
            }
            writeLibraryFile(osPath, "rxtxSerial.dll");
        }
        if (Platform.isLinux()) {
            if (Platform.is64Bit()) {
                osPath = "linux-x86_64";
            } else {
                osPath = "linux-i386";
                writeLibraryFile(osPath, "librxtxParallel.so");
            }
            writeLibraryFile(osPath, "librxtxSerial.so");
        }

    }

    /**
     * 写入库文件
     *
     * @param osPath   操作系统
     * @param fileName 文件名
     */
    public static void writeLibraryFile(String osPath, String fileName) {
        logger.info("当前操作系统为：" + System.getProperty("os.name"));
        logger.info("当前操作系统架构为：" + System.getProperty("os.arch"));
        String javaHomeBin = System.getProperty("java.home.bin");
        logger.info("当前 java.home.bin 路径为：" + javaHomeBin);
        if (StringUtils.isNotEmpty(javaHomeBin)) {
            //获取java类库路径
            InputStream is = null;
            try {
                is = Main.class.getResourceAsStream("/library/" + osPath + "/" + fileName);
                logger.info("加载" + fileName);
                if (is != null) {
                    File file = new File(javaHomeBin + "\\" + fileName);
                    if (Platform.isLinux()) {
                        file = new File(javaHomeBin + "/" + fileName);
                    }
                    logger.info("文件路径为：" + file.getAbsolutePath());
                    if (!file.exists()) {
                        FileUtils.copyInputStreamToFile(is, file);
                        logger.info("写入动态链接库文件成功！");
                    } else {
                        logger.info("文件已存在，无需再次写入！");

                    }
                }
            } catch (Exception e) {
                logger.error("加载DLL/SO文件失败", e);
            } finally {
                IOUtils.closeQuietly(is);
            }
        } else {
            logger.error("java.home.bin 路径为空，需要手动复制 DLL/SO 文件到 <JAVA_HOME>/bin 目录下");
        }
    }
}
